<?php

namespace app\api\controller\ytjk;

use app\api\controller\Base;
use app\server\HredisServer;
use app\server\KyyUserService;
use app\server\RegionServer;
use \think\facade\Db;

class CheckHuawei extends Base
{
    public $redisServer;
    protected $now;
    protected $outTime = 20; //投广超时时间（秒）
    protected $oldUserTime = 60 * 60;  //老用户时间（秒）留存多久算老用户
    protected $currentVersion = 4;  //限制版本，低于该版本不用验证，直接通过

    protected $clientCacheTime = 60 * 60;  //客户端缓存屏蔽配置的时间（秒）

    protected $checkList;

    protected $resultCode = 1;

    protected $dumpPath = '/pages/Task';

    protected $blackCitys = '佛山,深圳,东莞,广州,西安,上海,福州,厦门,龙岩,南京,镇江,常州,杭州,成都,北京,香港,澳门,台湾';

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->now = time();
        $this->checkList = [
            'ip' => 1,
            'oaid' => 0,
            'city' => 1,
            'time' => 1, //华为投放没有时间戳
            'isOld' => 1,
            'version' => 1,
        ];
        $this->redisServer = app(HredisServer::class);
        $params = $this->params;
        $config = config($params['app']);
        $this->currentVersion = $config['quick']['huawei']['currentVersion'];
    }

    protected function pass($data)
    {
        $blackOaid = ['00000000-0000-0000-0000-000000000000'];
        $data['cacheTime'] = $this->clientCacheTime;
        $data['path'] = $this->dumpPath;
        $data['resCode'] = $this->resultCode;
        $params = $this->params;
        $fieldArray = ['app_name','app_version','producer','path','hap','uuid','utime','oaid','ip','ts','check_msg','address'];
        $adData = [];
        foreach($fieldArray as $value){
            $adData[$value] = $params[$value]??'';
        }
        $adData['res_code'] = $this->resultCode;
        $adData['call_status'] = 0;
        $adData['ymd'] = date('Ymd',$this->now);
        $adData['check_msg'] = $data['msg'];
        $adData['pass'] = $data['pass'];
        $table = 'app_ad_check';
        $row = find($table,'id,pass',['uuid'=>$adData['uuid']]);
        if(empty($row) || in_array($adData['oaid'],$blackOaid)){
            if(in_array($adData['oaid'],$blackOaid)){
                $adData['pass'] = -1;
            }
            add($table,$adData);
        }else{
            if($row['pass'] !== 1){
                edit($table,['id'=>$row['id']],$adData);
            }
        }
        app(KyyUserService::class)->getUser($this->params,['pass'=>$adData['pass'],'res_code'=>$adData['res_code']]);
        $this->success('success', $data);
    }
    protected function getIp(){
        return request()->ip();
    }

    public function index()
    {
        $params = $this->params;
        $noHapPass = 3;
        $msg = 'success';
        // 非hap验证
        if (empty($params['app_version'])) {
            $noHapPass = 0;
            $msg = 'invalid version';
            $this->resultCode = 10001;
        } else {
            if ($params['app_version'] < $this->currentVersion) {
                $noHapPass = 1;
                $msg = 'old version';
                $this->resultCode = 10002;
            }
        }
        if ($noHapPass == 3) {
            $uTime = $params['utime'];
            if ($this->now - $uTime > $this->oldUserTime) {
                $noHapPass = 1;
                $msg = 'old user';
                $this->resultCode = 10003;
            }
        }

        if (in_array($noHapPass, [0, 1])) {
            //非hap验证
            $this->pass(['pass' => $noHapPass, 'msg' => $msg]);
        } else {
            if (empty($params['hap'])) {
                // 没有hap链接
                $this->pass(['pass' => 10011, 'msg' => 'noHap']);
            } else {
                //hap验证
                $pass = 1;
                $checkList = $this->checkList;
                $hap = json_decode($params['hap'], true);
                // 时间戳验证
                if ($pass == 1 && $checkList['time'] == 1) {
                    if (!empty($hap['stamp'])) {
                        if ($hap['stamp'] - $params['ts'] > $this->outTime) {
                            $pass = 0;
                            $msg = 'invalid stamp';
                            $this->resultCode = 10004;
                        }
                    }
                }
                // ip验证
                if ($pass == 1 && $checkList['ip'] == 1) {
                    if (empty($hap['ip'])) {
                        $pass = 0;
                        $msg = 'invalid ip1';
                        $this->resultCode = 10005;
                    } else {
                        $clientIp = $this->getIp();
                        $this->params['ip'] = $params['ip'] = $clientIp;
                        $clientIpArr = explode('.', $clientIp);
                        $clientIpString = ($clientIpArr[0] ?? '') . ($clientIpArr[1] ?? '') . ($clientIpArr[2] ?? '');
                        $hapArr = explode('.', $hap['ip']);
                        $hapString = ($hapArr[0] ?? '') . ($hapArr[1] ?? '') . ($hapArr[2] ?? '');
                        if ($clientIpString !== $hapString) {
                            $pass = 0;
                            $msg = 'invalid ip2';
                            $this->resultCode = 10006;
                        }
                    }
                }
                // oaid验证
                if ($pass == 1 && $checkList['oaid'] == 1) {
                    if (empty($hap['oaid'])) {
                        $pass = 0;
                        $msg = 'invalid oaid';
                        $this->resultCode = 10007;
                    } else {
                        $clientOaid = $params['oaid'];
                        $hapOaid = $hap['oaid'];
                        if ($clientOaid !== $hapOaid) {
                            $pass = 0;
                            $msg = 'invalid oaid2';
                            $this->resultCode = 10008;
                        }
                    }
                }
                // 屏蔽地区验证
                if ($pass == 1 && $checkList['city'] == 1) {
                    $cityArr = explode(',', $this->blackCitys);
                    $ipArr = explode('.', $params['ip']);
                    $clientIp = $ipArr[0] . '.' . $ipArr[1] . '.' . $ipArr[2];
                    $redisAddress = $this->redisServer->hget('ipAddress', $clientIp);
                    if (!empty($redisAddress)) {
                        $this->params['address'] = $redisAddress;
                        $areaArr = explode('|', $redisAddress);
                        $clientCity = $areaArr[3];
                        if (in_array($clientCity, $cityArr)) {
                            $pass = 0;
                            $msg = '该地区不在范围内1';
                            $this->resultCode = 10009;
                        }
                    } else {
                        $regionServer = app(RegionServer::class);
                        $redisAddress = $regionServer->memorySearch($params['ip']);
                        $areaArr = explode('|', $redisAddress['region']);
                        if (isset($areaArr[3])) {
                            $this->params['address'] = $redisAddress['region']??'';
                            $clientCity = $areaArr[3];
                            if (in_array($clientCity, $cityArr)) {
                                $pass = 0;
                                $msg = '该地区不在范围内2';
                                $this->resultCode = 10010;
                            }
                        }
                    }
                }
                $this->pass(['pass' => $pass, 'msg' => $msg]);
            }
        }
    }

    public function native_check(){
        $nativeClickRate = 100; //自动点击概率
        $nativeSecondRate = 30; //第二次自动点击概率
        $nativeAlertRate = 100; //弹窗概率
        $nativeConfig = [
            'isClick'=>0,            //自动点击是否开启
            'nativeLockTime'=>15,   //原生广告上锁睡眠时间（秒）,多久时间内不能再次自动点击
            'nativeClickTime'=>10,  //原生广告页面停留后触发点击时间（秒）
            'nativeRate'=>0,        // 原生广告点击广告的概率（0-100）
            'closeClickRate'=>0,  //点击关闭按钮触发广告点击的概率（0-100）
            'alertShow'=>0,
            'alertMsg'=>'已为您准备更新版本，解锁更多功能，更多福利！'
        ];
        $params = $this->params;
        $pass = 0;
        if($this->now - $params['utime'] > 3600){
            $pass = 1;
        }
        if ($pass ==0 && $params['app_version'] < $this->currentVersion) {
            $pass = 1;
        }
        $this->success('success',$nativeConfig);
    }
}
